<?php

namespace App\Http\Controllers\Admin;

use App\Http\Config\ErrorCode;
use App\Library\Common;
use App\Models\Admin\Achievement;
use App\Models\Company;
use App\Models\Customer\CustomerBase;
use App\Models\User\UserBase;
use App\Models\User\UserWechat;
use Illuminate\Http\Request;
use App\Models\Admin\Branch;
use App\Library\UploadFile;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class UserController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    protected $fields = [
        'name'  => '',
        'email' => '',
        'sex'   => '',
        'mobile'=> '',
        'ach_status' => 0,
        'wechat_id' => '',
        'position' => '',
        'hiredate' => '',
        'company_id' => '',
        'power' => ''
    ];

    //管理员列表
    public function index()
    {
        return response()->json($this->returnData);
    }

    public function dataList(Request $request)
    {
        if (!$request->ajax()) {
            $this->returnData = ErrorCode::$admin_enum['request_error'];
            return response()->json($this->returnData);
        }
        $page_no = $request->post('page_no', 1);
        $page_size = $request->post('page_size', 10);
        $searchFilter = array(
            'sortName' => $request->post('sortName','id'),                                                  //排序列名
            'sortOrder' => $request->post('sortOrder','asc'),                                               //排序（desc，asc）
            'pageNumber' => $page_no,                                                                                   //当前页码
            'pageSize' => $page_size,                                                                                   //一页显示的条数
            'start' => ($page_no-1) * $page_size,                                                                       //开始位置
            'searchKey' => trim($request->post('search','')),                                               //搜索关键词
            'branch_id' => trim($request->post('branch_id','')),
            'company_id' => trim($request->post('company_id',''))
        );
        $adminUserModel = new UserBase();
        $data = $adminUserModel->getAdminUserListWithFilter($searchFilter);
        $this->returnData['data'] = $data;
        return response()->json($this->returnData);
    }

    public function adminList()
    {
        $adminUserModel = new UserBase();
        $fields = ['id','name'];
        $data = $adminUserModel->getAdminUserList($fields);
        $this->returnData['data'] = $data;
        return response()->json($this->returnData);
    }

    /* 管理员基础信息 */
    public function basic()
    {
        $userModel = new UserBase();
        $data = $userModel->getAdminBasic($this->AU['id']);
        $this->returnData['data'] = $data;
        return response()->json($this->returnData);
    }

    /* 管理员详情 */
    public function detail($id)
    {
        $userModel = new UserBase();
        $data = $userModel->getAdminDetailByID($id);
        if(!is_array($data) || count($data)<1){
            $this->returnData = ErrorCode::$admin_enum['not_exist'];
            $this->returnData['msg'] = '该数据不存在';
            return response()->json($this->returnData);
        }
        $this->returnData['data'] = $data;
        return response()->json($this->returnData);
    }

    //管理员添加
    public function create(Request $request)
    {
        $user = [];
        foreach (array_keys($this->fields) as $field) {
            $user[$field] = $request->post($field);
        }
        $user['status'] = 0;
        $user['password'] = bcrypt($request->post('password'));
        $user['power'] = $request->post('power');
        $branch_list = $request->post('branch');
        if($branch_list!=''){
            $branch_list = explode(',',$branch_list);
        }
        $adminUserModel = new UserBase();
        $res = $adminUserModel->validAdminUserRepeat(['mobile'=>$user['mobile'],'email'=>$user['email']]);
        if($res['is_repeat']==1){
            $this->returnData = $res['returnData'];
            return response()->json($this->returnData);
        }
        $data = array(
            'role_id' => $request->post('role_id'),
            'branch' => $branch_list
        );
        $user_id = $adminUserModel->adminUserInsert($user,$data);
        if(!$user_id){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '添加失败';
            return response()->json($this->returnData);
        }
        //异步增加企业微信账号
        if($request->input('set_qy_wechat')==1){
            $companyModel = new Company();
            $res = $companyModel->getCompanyByID($request->input('company_id'));
            $department = $res['wechat_channel_id'];
            $gender = $request->input('sex')=='女'?2:1;
            if($user['power']!='' && count($user['power'])>0){
                $arr = array(
                    'userid' => $request->input('wechat_id'),
                    'name' => $request->input('name'),
                    'mobile' => $request->input('mobile'),
                    'department' => $department,
                    'position' => $request->input('position'),
                    'gender' => $gender,
                    'email' => $request->input('email'),
                    'isleader' => 1
                );
            }else{
                $arr = array(
                    'userid' => $request->input('wechat_id'),
                    'name' => $request->input('name'),
                    'mobile' => $request->input('mobile'),
                    'department' => $department,
                    'position' => $request->input('position'),
                    'gender' => $gender,
                    'email' => $request->input('email')
                );
            }
            $arr2 = array(
                'user' => $request->input('wechat_id')
            );
            $emailarr = array(
                'userid' => $request->input('wechat_id'),
                "name" => $request->input('name'),
                'department' => $department,
                'position' => $request->input('position'),
                'mobile' => $request->input('mobile'),
                'gender' => $gender,
                'password' => $request->input('password'),
                'cpwd_login' => 1
            );
            $common = new Common();
            $common->setQyWechat($arr);
            $common->invitationUser($arr2);
            $common->setQyEmail($emailarr);
        }
        $this->returnData['msg'] = '添加成功';
        return response()->json($this->returnData);
    }

	//管理员修改
    public function edit(Request $request)
    {
        $id = $request->id;
        if($this->AU['id']!=1 && $this->AU['id']!=$id){
            $this->returnData = ErrorCode::$admin_enum['auth_fail'];
            return response()->json($this->returnData);
        }
        $user = [];
        foreach (array_keys($this->fields) as $field) {
            $user[$field] = $request->post($field);
        }
        $user['password'] = bcrypt($request->post('password'));
        $user['power'] = $request->post('power');
        $branch_list = $request->post('branch');
        if($branch_list!=''){
            $branch_list = explode(',',$branch_list);
        }
        $adminUserModel = new UserBase();
        $res = $adminUserModel->validAdminUserRepeat(['mobile'=>$user['mobile'],'email'=>$user['email']],$id);
        if($res['is_repeat']==1){
            $this->returnData = $res['returnData'];
            return response()->json($this->returnData);
        }
        $data = array(
            'role_id' => (int)$request->post('role_id'),
            'branch' => $branch_list
        );
        $result = $adminUserModel->adminUserUpdate($id,$user,$data);
        if(!$result){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '修改失败';
            return response()->json($this->returnData);
        }
        //异步修改企业微信账号
        $companyModel = new Company();
        $res = $companyModel->getCompanyByID($request->input('company_id'));
        $department = $res['wechat_channel_id'];
        $gender = $request->input('sex')=='女'?2:1;
        $arr = array(
            'userid' => $request->input('wechat_id'),
            'name' => $request->input('name'),
            'mobile' => $request->input('mobile'),
            'department' => $department,
            'position' => $request->input('position'),
            'gender' => $gender,
            'email' => $request->input('email')
        );
        if($user['power']!='' && count($user['power'])>0){
            $arr['isleader'] =1;
        }
        $emailarr = array(
            'userid' => $request->input('wechat_id'),
            "name" => $request->input('name'),
            'department' => $department,
            'position' => $request->input('position'),
            'mobile' => $request->input('mobile'),
            'gender' => $gender
        );
        $arr2 = array(
            'user' => $request->input('wechat_id')
        );
        $common = new Common();
        $common->setQyWechat($arr,2);
        $common->setQyEmail($emailarr,2);
        $this->returnData['msg'] = '修改成功';
        return response()->json($this->returnData);
    }

    /* 管理员删除 */
    public function delete($id)
    {
        $adminUserModel = new UserBase();
        $res = $adminUserModel->adminUserDelete($id);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '删除失败';
            return response()->json($this->returnData);
        }
        $this->returnData['msg'] = '删除成功';
        return response()->json($this->returnData);
    }
    
    /* 管理员操作 */
    public function ajax(Request $request)
    {
        if (!$request->ajax()) {
            $this->returnData = ErrorCode::$admin_enum['request_error'];
            return response()->json($this->returnData);
        }
        if (!isset($request->action) || !in_array($request->action,['synchronize','update_status'],true)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            return response()->json($this->returnData);
        }
        $id = $request->id;
        if($this->AU['id']!=1 && $this->AU['id']!=$id){
            $this->returnData = ErrorCode::$admin_enum['auth_fail'];
            return response()->json($this->returnData);
        }
        switch ($request->action){
            case 'synchronize':                                                                                         //同步企业账号
                $res = $this->_buildUserQYAccount($request);
                return response()->json($res);
                break;
            case 'update_status':                                                                                       //更改管理员状态(启用/禁用)
                $res = $this->_updateStatus($request);
                if($res['code']>0){
                    return response()->json($res);
                }
                break;
            default:
                $this->returnData = ErrorCode::$admin_enum['request_error'];
                return response()->json($this->returnData);
        }
        $adminUserModel = new UserBase();
        $result = $adminUserModel->adminUserUpdate($id,$res['data']);
        if(!$result){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '操作失败';
            return response()->json($this->returnData);
        }
        $this->returnData['msg'] = '操作成功';
        return response()->json($this->returnData);
	}

    /* 管理员操作 */
    public function editBasic(Request $request)
    {
        if (!$request->ajax()) {
            $this->returnData = ErrorCode::$admin_enum['request_error'];
            return response()->json($this->returnData);
        }
        if (!isset($request->action) || !in_array($request->action,['update_avatar','update_workstatus','update_basic'],true)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            return response()->json($this->returnData);
        }
        $id = $request->id;
        if($this->AU['id']!=1 && $this->AU['id']!=$id){
            $this->returnData = ErrorCode::$admin_enum['auth_fail'];
            return response()->json($this->returnData);
        }
        switch ($request->action){
            case 'update_avatar':                                                                                       //修改头像
                $res = $this->_updateUserAvatar($request);
                if($res['code']>0){
                    return response()->json($res);
                }
                break;
            case 'update_workstatus':                                                                                   //更改工作状态
                $res = $this->_updateWorkStatus($request);
                if($res['code']>0){
                    return response()->json($res);
                }
                break;
            case 'update_basic':                                                                                        //修改基础信息
                $res = $this->_updateUserBaseInfo($request,$id);
                if($res['code']>0){
                    return response()->json($res);
                }
                break;
            default:
                $this->returnData = ErrorCode::$admin_enum['request_error'];
                return response()->json($this->returnData);
        }
        $adminUserModel = new UserBase();
        $result = $adminUserModel->adminUserUpdate($id,$res['data']);
        if(!$result){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '操作失败';
            return response()->json($this->returnData);
        }
        $this->returnData['msg'] = '操作成功';
        return response()->json($this->returnData);
	}

    //业绩和用户转移
    public function exchangeOrder(Request $request)
    {
        $touid = $request->input("exchange_user");
        if($touid==null){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '转移管理员不能为空';
            return response()->json($this->returnData);
        }
        $id = $request->input("uid");
        if($id==null){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '参数错误';
            return response()->json($this->returnData);
        }
        $adminUserModel = new UserBase();
        $user_list = $adminUserModel->getAdminSubuser($this->AU["id"]);
        if(!in_array($id,$user_list)){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '无权转移';
            return response()->json($this->returnData);
        }
        DB::beginTransaction();
        $membersModel = new CustomerBase();
        $res_members_update = $membersModel->getExchangeRecommend($id,['recommend'=>$touid]);
        $achievementModel = new Achievement();
        $res_achievement_update = $achievementModel->achievementUpdateByColumn('admin_users_id',$id,['admin_users_id'=>$touid]);
        if(!$res_members_update || !$res_achievement_update){
            DB::rollback();
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '转移失败';
            return response()->json($this->returnData);
        }
        DB::commit();
        $this->returnData['msg'] = '转移成功';
        return response()->json($this->returnData);
    }

    private function _buildUserQYAccount($request)
    {
        $id = $request->id;
        $userWechatModel = new UserWechat();
        $res = $userWechatModel->buildQYUser($id);
        return $res;
    }

    /* 更改用户头像 */
    private function _updateUserAvatar($request)
    {
        $self_returnData = $this->returnData;
        $file = $request->file('avatar');
        if (!$file){
            $self_returnData = ErrorCode::$admin_enum['params_error'];
            $self_returnData['msg'] = '文件不存在,请重新上传';
            return $self_returnData;
        }
        $result = (new UploadFile([
            'upload_dir' => './uploads/avatar/',
            'type'       =>['image/jpg','image/png','image/jpeg','image/bmp','image/gif']]
        ))->upload($file);
        if($result['code']>0) {
            return $result;
        }
        $self_returnData['data'] = ['wechat_pic' => $result['data']];
        return $self_returnData;
    }

	/* 更新管理员状态 */
    private function _updateStatus($request)
    {
        $self_returnData = $this->returnData;
        $status = trim($request->post('status',''));
        if($status==null || !in_array(strval($status),['0','1'],true)){
            $self_returnData = ErrorCode::$admin_enum['params_error'];
            return $self_returnData;
        }
        $self_returnData['data'] = ['status' => $status];
        return $self_returnData;
    }

    /* 打卡签到更新 */
    private function _updateWorkStatus($request)
    {
        $self_returnData = $this->returnData;
        $status = trim($request->post('work_status',''));
        if($status==null || !in_array(strval($status),['0','1'],true)){
            $self_returnData = ErrorCode::$admin_enum['params_error'];
            return $self_returnData;
        }
        $work_status = $request->post('work_status');
        $work_time = Carbon::now()->toDateTimeString();
        if($work_time <= (substr($work_time,0,10).' 08:00:00')){
            $work_time =  Carbon::now()->subDays(1)->toDateTimeString();
        }
        $self_returnData['data'] = ['work_status' => $work_status,'work_time' => $work_time];
        return $self_returnData;
    }

    /* 修改用户基础资料 */
    private function _updateUserBaseInfo($request,$id)
    {
        $self_returnData = $this->returnData;
        if(trim($request->post('sex',''))==''){
            $self_returnData = ErrorCode::$admin_enum['params_error'];
            $self_returnData['msg'] = '性别不能为空';
            return $self_returnData;
        }
        if(!in_array(trim($request->post('sex')),['男','女'],true)){
            $self_returnData = ErrorCode::$admin_enum['params_error'];
            $self_returnData['msg'] = '性别参数错误';
            return $self_returnData;
        }
        if(trim($request->post('mobile',''))==''){
            $self_returnData = ErrorCode::$admin_enum['params_error'];
            $self_returnData['msg'] = '手机号不能为空';
            return $self_returnData;
        }
        $adminUserModel = new UserBase();
        $res = $adminUserModel->validAdminUserRepeat(['mobile'=>$request->post('mobile')],$id);
        if($res['is_repeat']==1){
            $self_returnData = $res['returnData'];
            return $self_returnData;
        }
        $data = array(
            'sex' => $request->post('sex'),
            'mobile' => $request->post('mobile')
        );
        if(trim($request->post('password',''))!=''){
            $data['password'] = bcrypt(trim($request->post('password')));
        }
        $self_returnData['data'] = $data;
        return $self_returnData;
    }
}
